package com.redxun.config;

import com.redxun.auth.filter.LoginProcessSetTenantFilter;
import com.redxun.auth.handler.OauthLogoutSuccessHandler;
import com.redxun.auth.mobile.MobileAuthenticationSecurityConfig;
import com.redxun.auth.openid.OpenIdAuthenticationSecurityConfig;
import com.redxun.core.auth.config.DefaultResourceServerConf;
import com.redxun.core.auth.config.DefaultSecurityHandlerConfig;
import com.redxun.core.common.constant.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 资源服务器配置
 *
 * @author aj
 * @date 2019/10/5
 */
@Configuration
@EnableResourceServer
@Import(DefaultSecurityHandlerConfig.class)
public class ResourceServerConfig extends DefaultResourceServerConf {

    @Autowired
    private OpenIdAuthenticationSecurityConfig openIdAuthenticationSecurityConfig;

    @Autowired
    private MobileAuthenticationSecurityConfig mobileAuthenticationSecurityConfig;

    @Autowired
    private LogoutHandler oauthLogoutHandler;

    @Autowired(required = false)
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public HttpSecurity setAuthenticate(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) {
        return authorizedUrl.access("@permissionService.hasPermission(request, authentication)").and();
    }

    /**
     * 留给子类重写扩展功能
     *
     * @param http
     */
    @Override
    public HttpSecurity setHttp(HttpSecurity http) {
        try {
            http.logout()
                    .logoutUrl(SecurityConstants.LOGOUT_URL)
                    .logoutSuccessHandler(new OauthLogoutSuccessHandler())
                    .addLogoutHandler(oauthLogoutHandler)
                    .clearAuthentication(true)
                    .and()
                    .apply(openIdAuthenticationSecurityConfig)
                    .and()
                    .apply(mobileAuthenticationSecurityConfig)
                    .and()
                    .addFilterBefore(new LoginProcessSetTenantFilter(), UsernamePasswordAuthenticationFilter.class)
                    .csrf().disable()
                    // 解决不允许显示在iframe的问题
                    .headers().frameOptions().disable().cacheControl();


            // 基于密码 等模式可以无session,不支持授权码模式
            if (authenticationEntryPoint  !=  null) {
                http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
                http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            } else {
                // 授权码模式单独处理，需要session的支持，此模式可以支持所有oauth2的认证
                http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return http;
    }
}
